#include<iostream>
#include"../comm/httplib.h"
#include"../comm/jsoncpp.hpp"
#include"../comm/log.hpp"
#include"../comm/ServiceRegister.hpp"
#include"Controler.hpp"
using namespace std;
using namespace httplib;
using namespace Ns_Log;
int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        cout<<"Usage: ./compile_server port"<<endl;
        return 0;
    }
    int port=atoi(argv[1]);
    
    Server svr;
    Controler con;
    svr.Post("/compile_run",[&con](const Request& req,Response& rep)
    {
        log(INFO,"收到一个编译请求...content: ");
        //反序列化
        Json::Value root;
        UnSerialize(root,req.body);
        string code=root["code"].asString();
        string _stdin=root["stdin"].asString();
        
        int status;
        string result_message;
        con.compile_run(code,_stdin,status,result_message);//调用编译运行服务
        log(DEBUG,"status: "+to_string(status)+" result_message: "+result_message);
        //序列化
        string resp_json;
        Json::Value resp_root;
        resp_root["status"]=status;
        resp_root["result_message"]=result_message;
        Serialize(resp_root,resp_json);

        rep.set_content(resp_json,"application/json");
    });
    log(INFO,to_string(port)+"端口上的编译服务启动成功!");

    //生命周期同服务器，如果编译服务器奔溃，租约会在ttl后失效，etcd服务器将键值对删除
    etcdtools::Register reg("127.0.0.1:2379");//etcd服务器的ip地址和端口号   
    bool resp=reg.regist("/service/compiler","127.0.0.1:"+to_string(port));//微服务的ip地址和端口号
    if(resp)
    log(INFO,"etcd regist success,127.0.0.1 : "+to_string(port)+"可以提供"+"/service/compiler服务");


    svr.listen("0.0.0.0",port);
    return 0;
}